package com.ld.poetry.controller;


import com.ld.poetry.config.PoetryResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.UUID;

@RestController
@RequestMapping("/upload")
public class UploadController {

    // 文件上传后的存储路径
    private static final String UPLOAD_PATH = "/home/file/music";


    @RequestMapping("/musicFile")
    public PoetryResult<String> musicFile(@RequestParam("file") MultipartFile file) {
        try {
            // 创建上传目录（如果不存在）
            Path uploadPath = Paths.get(UPLOAD_PATH);
            Files.createDirectories(uploadPath);

            // 获取文件名并进行清理
            String originalFileName = file.getOriginalFilename();
            String fileName = sanitizeFileName(originalFileName);

            // 检查文件类型
            if (!isValidFileType(fileName)) {
                return PoetryResult.fail("不支持的文件类型");
            }

            // 构建文件路径
            Path filePath = uploadPath.resolve(fileName);

            // 将文件保存到服务器
            try (InputStream inputStream = file.getInputStream()) {
                Files.copy(inputStream, filePath);
            }

            // 获取静态资源URL
            String formattedPath = getStaticResourceUrl(fileName);
            return PoetryResult.success(formattedPath);

        } catch (Exception e) {
            // 记录日志
            return PoetryResult.fail("文件上传失败");
        }


    }

    // 辅助方法
    private String sanitizeFileName(String fileName) {
        // 使用UUID生成随机文件名
        String uuidPart = UUID.randomUUID().toString().substring(0, 8);
        String extension = fileName.substring(fileName.lastIndexOf('.'));
        return uuidPart + extension;
    }

    private boolean isValidFileType(String fileName) {
        // 检查文件类型是否允许
        String extension = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase();
        return Arrays.asList("mp3", "wav", "flac").contains(extension);
    }

    private String getStaticResourceUrl(String fileName) {
        // 从配置文件中读取静态资源URL前缀
        return "http://localhost:8081/static/music/" + fileName;
    }
}
